from typing import List
import os

from common.config.configUtils import configUtils
from common.fileManager.fileUtils import fileUtils
from faceSim.faceSimCalUtils import faceSimCalUtils
from modelBean.faceBean import faceBean

imgBasePath = configUtils.getConfigProperties("dataPath", "imgBasePath")
imgPrefix = configUtils.getConfigProperties("dataPath", "imgPrefix")

faceImgPathsMap = {}
faceVectorsMap = {}
faceObjectMap = {}


class faceInfoServiceImpl:



    def upFaceData(self,personId:str, personInfo: dict, faceGroup: int, faceImgs: List):
        faceInfo = []
        fileName, faceVector = None, None

        if not faceImgPathsMap.keys().__contains__(faceGroup):
            self.initDataToMem(faceGroup)

        for imageItem in faceImgs:
            fileName = fileUtils.getRandomName(imageItem.filename)
            imageItem.save(imgBasePath + fileName)
            faceVector = faceSimCalUtils.getFaceVector(imgBasePath + fileName)
            faceInfo.append({
                "filePath": fileName,
                "faceVector": faceVector
            })

        faceIns = faceBean(personId=personId,personInfo=personInfo, faceGroup=faceGroup, faceInfo=faceInfo)

        faceIns.save()

        faceImgPathsMap[faceGroup].append(fileName)
        faceVectorsMap[faceGroup].append(faceVector)
        faceObjectMap[faceGroup].append(personInfo)

        return {"rs": 1}

    #update face data
    def updateFaceData(self,personId:str, personInfo: dict, faceGroup: int, faceImgs: List):
        # 1.delete faces
        persons = faceBean.objects(personId=personId, faceGroup=faceGroup)
        persons.update(state=0)
        #2.清空内存中的数据
        self.clearMemData(faceGroup)
        #3.从新插入
        self.upFaceData(personId,personInfo,faceGroup,faceImgs)

        return {"rs": 1,"msg":"update success"}

    def delFaceData(self,personId:str,faceGroup: int):
        # 1.delete faces
        persons = faceBean.objects(personId=personId, faceGroup=faceGroup)
        persons.update(state=0)
        # 2.清空内存中的数据
        self.clearMemData(faceGroup)
        #3.初始化内存数据
        self.initDataToMem(faceGroup)

        return {"rs": 1, "msg": "delete success"}


    def getSimFace(self, faceGroup: int, faceImg):

        faceGroup=int(faceGroup)
        if not faceImgPathsMap.keys().__contains__(faceGroup):
            self.initDataToMem(faceGroup)

        # 1.save file
        fileName = fileUtils.getRandomName(faceImg.filename)
        filePath = imgBasePath + fileName
        faceImg.save(filePath)
        # 2. get face vector
        faceVector = faceSimCalUtils.getFaceVector(filePath)

        if faceVector is None:
            return {
                "rs": -1,
                "msg": "no face detected"
            }
        if faceVectorsMap[faceGroup] is None or len(faceVectorsMap[faceGroup])==0:
            return {
                "rs": -1,
                "msg": "no faces in this faceGroup"
            }
        print(faceVectorsMap[faceGroup])
        index, score = faceSimCalUtils.getSimFace(faceVectorsMap[faceGroup], faceVector)

        # 3.获取人脸关键点

        keyPointfileName = fileUtils.getRandomName(faceImg.filename)
        keyPointImgPath = imgBasePath + keyPointfileName
        faceSimCalUtils.drawFaceKeyPoint(filePath, keyPointImgPath)

        return {"rs": 1, "imgPath": imgPrefix + faceImgPathsMap[faceGroup][index],
                "personInfo": faceObjectMap[faceGroup][index],
                "keyPointFace": imgPrefix + keyPointfileName,
                "score": str(int((1 - score) * 100)) + "%"
                }

    def ininStarFaceData(self, faceGroup, filePath):
        files = os.listdir(filePath)

        count = 0
        for fileItem in files:
            if fileItem.find(".jpeg") < 0 and fileItem.find(".png") < 0:
                continue
            faceInfo = []
            startName = fileItem.split(".")[0]

            faceEnconding = faceSimCalUtils.getFaceVector(filePath + "/" + fileItem)
            if faceEnconding is not None:
                faceInfo.append({
                    "filePath": fileItem,
                    "faceVector": faceEnconding
                })
            faceIns = faceBean(personInfo=startName, faceGroup=faceGroup, faceInfo=faceInfo)

            faceIns.save()
            print("----------" + str(count) + "----------")
            count += 1
            print(startName)

        return {"rs": 1}

    def clearMemData(self,faceGroup: int):
        print("清除数据 faceGroup:"+str(faceGroup))
        if faceImgPathsMap.keys().__contains__(faceGroup):
            faceImgPathsMap.pop(faceGroup)
            faceVectorsMap.pop(faceGroup)
            faceObjectMap.pop(faceGroup)
        print("faceObjectMap:" + str(faceObjectMap))


    def initDataToMem(self, faceGroup: int):

        print("-----------------------------")
        print("初始化数据：" + str(faceGroup))

        faceObjectInfo = []
        faceImgPaths = []
        faceVectors = []

        faceBeans = faceBean.objects(faceGroup=faceGroup,state=1)
        for faceItem in faceBeans:
            faceInfoJSON = faceItem['faceInfo']
            for faceIteminfo in faceInfoJSON:
                faceImgPaths.append(faceIteminfo["filePath"])
                faceVectors.append(faceIteminfo["faceVector"])
                faceObjectInfo.append(faceItem['personInfo'])

        faceGroupInx=int(faceGroup)
        faceImgPathsMap[faceGroupInx] = faceImgPaths
        faceVectorsMap[faceGroupInx] = faceVectors
        faceObjectMap[faceGroupInx] = faceObjectInfo

        print(faceImgPathsMap)
        print(faceVectorsMap)
        print(faceObjectMap)

        print("******************************")

